import Vue from 'vue'
import Stomp from "stompjs";
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
  MQTT_TOPIC,
} from "@/utils/mqtt";

export default {
  client: null,
  isConnect: false, // 是否连接
  timeId: null,
  onConnected() {
    this.isConnect = true
    console.log('连接成功')
    //订阅的频道
    this.client.subscribe(MQTT_TOPIC, this.responseCallback, this.onFailed);
  },
  onFailed(msg) {
    this.isConnect = false
    console.log('连接失败')
    console.log(msg)
    this.onPollConnect()
  },
  //成功时的回调函数
  responseCallback(msg) {
    //接收消息的处理
    console.log("订阅成功");
    const data = JSON.parse(msg.body)
      // 注册通知
      if(data.type === 'register') {
        Vue.prototype.$notify.success({
          title: data.body.title,
          message: data.body.desc,
          duration: 0
        });
      }
  },
  //连接
  connect() {
    this.client = Stomp.client(MQTT_SERVICE)
    this.client.connect(MQTT_USERNAME, MQTT_PASSWORD, this.onConnected.bind(this), this.onFailed.bind(this));
    this.client.debug = null
  },
  // 断开
  onClose() {
    this.client.disconnect(() => {
      console.log('已断开')
      console.log('尝试重连')
      this.connect()
    })
  },
  // 轮询重连
  onPollConnect() {
    // 每5秒发起连接
    this.timeId = setInterval(() => {
      if(this.isConnect) {
        clearInterval(this.timeId)
        return
      }
      this.onClose()
    },5000)
  }
}
